package linechart;

import log4j.LogUtil;

//得到实时上报AI值和其label
public class RealAIInfo {

	private String devId = "";
	private String devName = "";
	private Number value;
	private String label;

	//内部线程相关属性
	private boolean isQueryOK = true;
	private boolean isFirst = true;
	private QueryThread queryThread;
	
	public RealAIInfo(String devId, String devName) {
		setDeviceInfo(devId, devName);
		queryThread = new QueryThread();
		queryThread.setName("AI-Query-Thread-" + devId);
		queryThread.setRealAIInfo(this);
		queryThread.start();
	}

	public void setRealInfo(Number num, String label) {
		this.value = num;
		this.label = label;
	}

	public void setDeviceInfo(String devId, String devName) {
		this.devId = devId;
		this.devName = devName;
	}

	public synchronized boolean queryInfo() {     
        if (isFirst) {
            isFirst = false;
        } else {
            queryThread.query();
        }
        return isQueryOK;
    }
	
	public String getDevId() {
		return devId;
	}

	public void setDevId(String devId) {
		this.devId = devId;
	}

	public String getDevName() {
		return devName;
	}

	public void setDevName(String devName) {
		this.devName = devName;
	}

	public Number getValue() {
		return value;
	}

	public void setValue(Number value) {
		this.value = value;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public boolean isQueryOK() {
		return isQueryOK;
	}

	public void setQueryOK(boolean isQueryOK) {
		this.isQueryOK = isQueryOK;
	}

	public boolean isFirst() {
		return isFirst;
	}

	public void setFirst(boolean isFirst) {
		this.isFirst = isFirst;
	}

	public QueryThread getQueryThread() {
		return queryThread;
	}

	public void setQueryThread(QueryThread queryThread) {
		this.queryThread = queryThread;
	}

	// 查询实时信息的线程內部类
	class QueryThread extends Thread {
		private RealAIInfo realAIInfo;
		private boolean isRun = true;

		public void setRealAIInfo(RealAIInfo realAIInfo) {
			this.realAIInfo = realAIInfo;
		}

		public void setIsRun(boolean isRun) {
			this.isRun = isRun;
		}

		public synchronized void query() {
			notify();
		}

		public Number generateNumber() {
			Number i = 100 * Math.random();
			return i;
		}

		private void deal() {
			int i = 1;// 具体应用切换成具体业务逻辑
			if (i == 1) {
				realAIInfo.setQueryOK(true);
				Number num = generateNumber();
				String label = "demo";
				LogUtil.debug("一条实时信息返回.");
				realAIInfo.setRealInfo(num, label);
			} else {
				realAIInfo.setQueryOK(false);
			}
		}

		private synchronized void waitfor() {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		public void run() {
			while (isRun) {
				LogUtil.debug("实时信息查询线程启动.");
				deal();
				waitfor();
			}
		}
	}
}